package thread_ex;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

class MyFrame01 extends JFrame implements ActionListener{
	JLabel img1 = new JLabel(new ImageIcon("c:\\1.jpg"));
	JLabel img2 = new JLabel(new ImageIcon("c:\\2.jpg"));
	JLabel img3 = new JLabel(new ImageIcon("c:\\3.jpg"));
	JButton btn = new JButton("Start");
	int endX = 0;
	static int rank = 0;
	
	public MyFrame01(){
		super("race");
		
		setLayout(null);
		img1.setBounds(10,50,50,50);
		img2.setBounds(10,110,50,50);
		img3.setBounds(10,170,50,50);
		btn.setBounds(10,250,100,30);
		add(img1); // 앞에 this. 생략
		add(img2);
		add(img3);
		add(btn);
		btn.addActionListener(this);
		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(700,400);
		setVisible(true);
		endX = getWidth(); // 프레임의 가로길이를 얻어온다.
		
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		rank = 0; // 버튼을 눌렀을때, 각 이미지를 이동시키는 스레드 실행시키기
		
		new ImgMove(img1).start();
		new ImgMove(img2).start();
		new ImgMove(img3).start();		
	}	
	
	class ImgMove extends Thread{
		JLabel img;
		
		public ImgMove(JLabel img){
			this.img=img;
		}
		
		public void run(){
			img.setLocation(10, img.getY());
			Random rnd = new Random();
			int x = 0;
			while(true){
				x = rnd.nextInt(60);
				int mx = img.getX()+x;
				img.setLocation(mx, img.getY());
				if(img.getX() >= (endX - 30 - img.getWidth())){
					++rank;
					img.setToolTipText("등수 : " + rank);
					break;
				}
				try{
					Thread.sleep(1000);
				}catch(InterruptedException e){
					System.out.println(e.getMessage());
				}
			}
		}		
	}
}

public class Test01_Imgmove {
	
	public static void main(String[] args) {
		new MyFrame01();
		
	}
}
